<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-row :justify="'space-between'">
        <el-col :span="16">
          <el-form-item>
            <el-input
              v-model="queryParams.searchValue"
              placeholder="请输入搜索内容"
              clearable
              style="width: 200px; margin-right: 10px"
              @keyup.enter="handleQuery"
            />
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-form-item>
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['statistics:statistics:export']">导出</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item label="时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-row>
    </el-form>

   
    <div class="age-statistics">
      <div ref="ageChartRef" style="width: 100%; height: 400px;"></div>
    </div>

    <el-row :gutter="10" class="mb8"> 
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="statisticsList" 
      @selection-change="handleSelectionChange"
      :show-summary="true"
      :summary-method="getSummaries"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="年龄段" align="center">
        <template #default="scope">
          {{ formatAgeRange(scope.row.age) }}
        </template>
      </el-table-column>
      <el-table-column label="人次" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['statistics:statistics:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['statistics:statistics:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改患者统计对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="statisticsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年龄" prop="age">
          <el-input 
            v-model="form.age" 
            placeholder="请输入年龄" 
            type="number"
            :min="0"
            :max="150"
            class="no-arrows"
          />
        </el-form-item>
        <el-form-item label="人次" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入人次" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Statistics">
import { listStatistics, getStatistics, delStatistics, addStatistics, updateStatistics } from "@/api/statistics/statistics";
import * as echarts from 'echarts'
import { onMounted, ref, onUnmounted } from 'vue'

const { proxy } = getCurrentInstance();

const statisticsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const ageStatistics = ref([]);

const data = reactive({
    form: {
        id: null,
        age: '',
        remark: null
    },
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        age: null,
        remark: null
    },
    rules: {
        age: [
            { required: true, message: "年龄不能为空", trigger: "blur" },
            { 
                validator: (rule, value, callback) => {
                    if (value === '' || value === null) {
                        callback();
                        return;
                    }
                    const age = Number(value);
                    if (age >= 0 && age <= 150) {
                        callback();
                    } else {
                        callback(new Error('年龄必须在0-150之间'));
                    }
                },
                trigger: 'blur'
            }
        ]
    }
});

const { queryParams, form, rules } = toRefs(data);

// 声明图表实例
const ageChartRef = ref(null)
let ageChart = null

// 初始化图表
const initAgeChart = (data) => {
  if (ageChart) {
    ageChart.dispose()
  }
  
  ageChart = echarts.init(ageChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['0-10岁', '11-20岁', '21-30岁', '31-40岁', '41-50岁', 
             '51-60岁', '61-70岁', '71-80岁', '80岁以上'],
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '人次',
      minInterval: 1
    },
    series: [{
      data: data,
      type: 'bar',
      itemStyle: {
        color: '#8B89FF'
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  }
  ageChart.setOption(option)
}

/** 查询患者统计列表 */
const getList = async() => {
  loading.value = true
  try {
    const response = await listStatistics(queryParams.value)
    
    // 计算合计
    const totalCount = response.rows.reduce((sum, item) => {
      return sum + Number(item.remark || 0)
    }, 0)
    
    // 初始化年龄段统计数据
    const ageGroups = {
      '0-10': 0,
      '11-20': 0,
      '21-30': 0,
      '31-40': 0,
      '41-50': 0,
      '51-60': 0,
      '61-70': 0,
      '71-80': 0,
      '80+': 0
    };

    // 统计每个年龄段的人次
    response.rows.forEach(item => {
      const age = Number(item.age);
      const count = Number(item.remark) || 0;
      
      // 根据年龄判断所属区间
      if (age >= 0 && age <= 10) ageGroups['0-10'] += count;
      else if (age >= 11 && age <= 20) ageGroups['11-20'] += count;
      else if (age >= 21 && age <= 30) ageGroups['21-30'] += count;
      else if (age >= 31 && age <= 40) ageGroups['31-40'] += count;
      else if (age >= 41 && age <= 50) ageGroups['41-50'] += count;
      else if (age >= 51 && age <= 60) ageGroups['51-60'] += count;
      else if (age >= 61 && age <= 70) ageGroups['61-70'] += count;
      else if (age >= 71 && age <= 80) ageGroups['71-80'] += count;
      else if (age > 80) ageGroups['80+'] += count;
    });

    // 转换为图表所需的数据格式
    const chartData = Object.values(ageGroups);
    
    // 更新图表
    initAgeChart(chartData);
    
    // 更新表格数据
    statisticsList.value = response.rows;
    total.value = response.total;

  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getStatistics(_id).then(response => {
        console.log('获取到的修改数据:', response.data);  // 添加日志
        form.value = {
            id: response.data.id,
            age: response.data.age,  // 确保使用正确的字段名
            remark: response.data.remark
        };
        open.value = true;
        title.value = "修改患者统计";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["statisticsRef"].validate(valid => {
        if (valid) {
            const submitData = {
                id: form.value.id,
                age: form.value.age,  // 确保使用age字段
                remark: form.value.remark
            };
            console.log('提交的修改数据:', submitData);  // 添加日志

            if (form.value.id != null) {
                updateStatistics(submitData).then(response => {
                    if (response.code === 200) {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    } else {
                        proxy.$modal.msgError(response.msg || "修改失败");
                    }
                });
            } else {
                addStatistics(submitData).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    age: '',
    remark: null
  };
  proxy.resetForm("statisticsRef");
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除患者统计编号为"' + _ids + '"的数据项？').then(function() {
    return delStatistics(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('statistics/statistics/export', {
    ...queryParams.value
  }, `statistics_${new Date().getTime()}.xlsx`)
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 修改年龄区间格式化函数
const formatAgeRange = (age) => {
    if (!age && age !== 0) return '暂无';
    const ageNum = Number(age);
    
    if (ageNum >= 0 && ageNum <= 10) return '0-10岁';
    if (ageNum >= 11 && ageNum <= 20) return '11-20岁';
    if (ageNum >= 21 && ageNum <= 30) return '21-30岁';
    if (ageNum >= 31 && ageNum <= 40) return '31-40岁';
    if (ageNum >= 41 && ageNum <= 50) return '41-50岁';
    if (ageNum >= 51 && ageNum <= 60) return '51-60岁';
    if (ageNum >= 61 && ageNum <= 70) return '61-70岁';
    if (ageNum >= 71 && ageNum <= 80) return '71-80岁';
    if (ageNum > 80) return '80岁以上';
    
    return `${age}岁`;
};

// 监听窗口大小变化，调整图表大小
const handleResize = () => {
  ageChart && ageChart.resize()
}

// 添加合计计算方法
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    if (index === 1) {  // 患者卡号列
      sums[index] = '';
      return;
    }
    if (index === 2) {  // 年龄列
      sums[index] = '';
      return;
    }
    if (index === 3) {  // 人次列
      const values = data.map(item => Number(item.remark));
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
    } else {
      sums[index] = '';
    }
  });
  return sums;
};

// 添加固定人次的统计数据
const fixedAgeStatistics = ref([
  { ageRange: '80岁以上', count: 60, percentage: '20.00' },
  { ageRange: '71-80岁', count: 50, percentage: '16.67' },
  { ageRange: '61-70岁', count: 40, percentage: '13.33' },
  { ageRange: '51-60岁', count: 30, percentage: '10.00' },
  { ageRange: '41-50岁', count: 20, percentage: '6.67' },
  { ageRange: '31-40岁', count: 10, percentage: '3.33' },
  { ageRange: '21-30岁', count: 0, percentage: '0.00' },
  { ageRange: '11-20岁', count: 0, percentage: '0.00' },
  { ageRange: '0-10岁', count: 0, percentage: '0.00' }
]);

// 处理年龄输入
const handleAgeInput = (value) => {
    // 只允许输入数字
    form.value.age = value.replace(/[^\d]/g, '');
    // 如果输入的数字大于150，则设置为150
    if (Number(form.value.age) > 150) {
        form.value.age = '150';
    }
};

onMounted(() => {
  getList()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  if (ageChart) {
    ageChart.dispose()
    ageChart = null
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.age-statistics {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

/* 添加统计表样式 */
.el-table {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
}

/* 隐藏数字输入框的上下箭头 */
.no-arrows input::-webkit-outer-spin-button,
.no-arrows input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.no-arrows input[type="number"] {
  -moz-appearance: textfield;
}
</style>
